package com.turing.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.util.StringUtils;
import com.turing.merchant.entity.*;
import com.turing.merchant.feign.AuthService;
import com.turing.merchant.mapper.*;
import com.turing.merchant.service.MerchantCategoryService;
import com.turing.merchant.service.MerchantService;
import enums.ErrorCode;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import result.Result;

import javax.annotation.Resource;
import javax.management.BadAttributeValueExpException;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.util.*;
import java.util.List;

/**
 * @author 28123
 * @description 针对表【merchant(商家)】的数据库操作Service实现
 * @createDate 2023-05-08 13:26:25
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant>
        implements MerchantService {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private HttpServletRequest request;
    @Resource
    private AuthService authService;

    @Override
    public Result merList(String merchantName, String loginAccount, String merchantPhone, String categoryId, Integer cdType, String longitude, String latitude, String cityId, Integer sortType, Integer orderType, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<String> merIds = new ArrayList<>();
        Map redisData = new HashMap();
        ZSetOperations zsetOps = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple> redisSet;
        if (sortType == 2) {
            if (pageNum != null) {
                if (orderType == 1) {
                    redisSet = zsetOps.reverseRangeWithScores("merchantComments", (pageNum - 1) * pageSize, pageNum * pageSize - 1);
                } else {
                    redisSet = zsetOps.rangeWithScores("merchantComments", (pageNum - 1) * pageSize, pageNum * pageSize - 1);
                }
            } else {
                if (orderType == 1) {
                    redisSet = zsetOps.reverseRangeWithScores("merchantComments", 0, -1);
                } else {
                    redisSet = zsetOps.rangeWithScores("merchantComments", 0, -1);
                }
            }
            for (ZSetOperations.TypedTuple typedTuple : redisSet) {
                merIds.add((String) typedTuple.getValue());
            }
        } else {
            redisSet = zsetOps.rangeWithScores("merchantComments", 0, -1);
            for (ZSetOperations.TypedTuple typedTuple : redisSet) {
                redisData.put(typedTuple.getValue(), typedTuple.getScore());
            }
        }
        List<Map> list = baseMapper.merList(merchantName, loginAccount, merchantPhone, categoryId, cdType, longitude, latitude, cityId, sortType, orderType, pageNum, pageSize, merIds);
        if (sortType != 2) {
            for (Map map : list) {
                map.put("merchantComments", redisData.get(map.get("merchantId")));
            }
        }
        if (list.size() == 0) {
            return Result.fail(ErrorCode.NODATA);
        }
        return Result.success(new PageInfo<>(list));
    }

    @Override
    public Result getMerById(String id) {
        List<Map> list1 = baseMapper.getMerById(id);
        if (list1.size() == 0) {
            return Result.fail(ErrorCode.NODATA);
        }
        return Result.success(list1.get(0));
    }

    @Override
    public Result merEdit(JSONObject jsonObject) {
        Merchant merchant = JSONObject.toJavaObject(jsonObject, Merchant.class);
        String adminIds = jsonObject.getString("adminIds");
        String categoryId1 = jsonObject.getString("categoryId");
        MerchantCategory merchantCategory = JSONObject.toJavaObject(jsonObject, MerchantCategory.class);
        int i = baseMapper.updateById(merchant);
        if (categoryId1 != null){
            String categoryId = merchantCategory.getCategoryId();
            if (!StringUtils.isNullOrEmpty(categoryId)) {
                categoryId = categoryId.substring(1, categoryId.length() - 1);
                List<String> list = Arrays.asList(categoryId.split(","));
                baseMapper.deleteCategoryId(merchantCategory);
                for (String s : list) {
                    MerchantCategory merchantCategory1 = new MerchantCategory();
                    merchantCategory1.setMerchantId(merchantCategory.getMerchantId());
                    merchantCategory1.setCategoryId(s);
                    String id = UUID.randomUUID() + "";
                    merchantCategory1.setMcId(id);
                    baseMapper.insertCategoryId(merchantCategory1);
                }
            }
        }
        if (i > 0) {
            return Result.success();
        } else {
            return Result.fail(ErrorCode.ERROR_EDIT);
        }
    }

    @Override
    public Result adminList(String merchantId, String cusNickname, String cusInfo, Integer sortType, Integer orderType, Integer pageNum, Integer pageSize) {

        //获取token
        String token = request.getHeader("Authorization");
        String tokenHead = "Bearer ";
        token = token.substring(tokenHead.length());
        //根据token获取id
        Result infoByToken = authService.getUserInfoByToken(token);
        JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(infoByToken.getData()));
        String cusId = jsonObject1.getString("username");

        if (pageNum!=null && pageSize!=null){
            PageHelper.startPage(pageNum,pageSize);
        } //没写粉丝数和关注状态,拉新总数

        List<String> merIds = new ArrayList<>();
        Map redisData = new HashMap();
        ZSetOperations zsetOps = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple> redisSet;
        if (sortType == 3){
            if (pageNum!=null){
                if (orderType==1){
                    redisSet = zsetOps.reverseRangeWithScores("cusComments", (pageNum - 1) * pageSize, pageNum * pageSize - 1);
                }else{
                    redisSet = zsetOps.rangeWithScores("cusComments", (pageNum - 1) * pageSize, pageNum * pageSize - 1);
                }
            }else{
                if (orderType==1){
                    redisSet = zsetOps.reverseRangeWithScores("cusComments", 0, -1);
                }else{
                    redisSet = zsetOps.rangeWithScores("cusComments", 0, -1);
                }
            }
            for (ZSetOperations.TypedTuple typedTuple : redisSet) {
                merIds.add((String) typedTuple.getValue());
            }
        }else{
            redisSet = zsetOps.rangeWithScores("cusComments", 0, -1);
            for (ZSetOperations.TypedTuple typedTuple : redisSet) {
                redisData.put(typedTuple.getValue(), typedTuple.getScore());
            }
        }

        List<Map> list = baseMapper.adminList(merchantId,cusNickname,cusInfo,sortType,orderType,pageNum,pageSize,merIds,cusId);
        if (sortType != 3){
            for (Map map : list) {
                map.put("cusComments",redisData.get(map.get("merchantId")));
            }
        }

        Map list1 = baseMapper.selectDianZhang(merchantId,cusNickname,cusInfo,sortType,orderType,pageNum,pageSize,merIds);
        Map map = new HashMap<>();
        map.put("adminList",list);
        map.put("keeper",list1);
        if (map.size() == 0){
            return Result.fail(ErrorCode.NODATA);
        }
        return Result.success(map);
    }

}




